<style type="text/css" scoped>
.product-info {
    width: 100%;
    display: flex;
    position: relative;
}
.confirm-btn {
    width: 100%;
    height: 44px;
    background: #dd3022;
    color: #fff;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.icon-close {
    position: absolute;
    right: 4px;
    top: 2px;
    font-size: 20px;
    color: #666;
}
.product-info .product-image {
    width: 2.8rem;
    height: 2.4rem;
    position: relative;
}
.product-info .product-image img {
    position: absolute;
    width: 2.6rem;
    height: 2.6rem;
    left: 6px;
    bottom: 7px;
    border-radius: 4px;
    box-shadow: 0 0 1px rgba(0,0,0,.5);
}
.product-info .product-tip {
    flex: 1;
    padding-left: 6px;
    padding-right: 6px;
    position: relative;
    justify-content: center;
    display: flex;
    flex-direction: column;
}
.product-name {
	font-size: 10px;
	overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
}
.product-price .dp-price {
	color: red;
	font-size: 16px;
}
.product-price .sc-price {
	margin-left: 6px;
	font-size: 10px;
	color: #666;
	text-decoration: line-through;
}
.product-detail-richtext {
    padding: 4px;
}
.product-detail {
	margin-top: 2px;
    font-size: 10px;
    color: #666;
}
.product-detail {
    margin-top: 2px;
    font-size: 12px;
    color: #666;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;    
}

.product-detail .selected-items {
	text-overflow: -o-ellipsis-lastline;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 1;
	line-clamp: 1;
	-webkit-box-orient: vertical;
	padding-right: 56px;
	flex: 1;
}
.product-detail .qty {
  	text-align: right;
  	position: absolute;
  	right: 0;
}

.specs-item {
    padding: 6px 0 6px 0;
}
.specs-item:not(:last-child) {
    margin-bottom: 1px;
}
.specs-item-button {
    margin-right: 6px;
    border-radius: 4px;
    display: inline-block;
    padding: 4px;
    font-size: 12px;
    text-align: center;
    box-shadow: 0 0 2px rgba(0,0,0,.2);
    min-width: 30px;
    margin-bottom: 4px;
}
.specs-item-name {
    height: 30px;
    line-height: 30px;
}
.specs-container {
    padding-left: 6px;
    background: #fff;
}

.product-num {
    padding: 8px;
    display: flex;
    font-size: 14px;
}

.product-num .tip {
    width: 100px;
    padding: 4px 0;
}
.action-btn-container {
    flex: 1;
}
.action-btn-container .action-btn-group {
    float: right;
    display: flex;
    box-sizing: border-box;
    width: 80px;
}
.action-btn-container .action-btn-group span {
    flex: 1;
    justify-content: center;
    align-items: center;
    display: flex;
    font-size: 14px;
}
.action-btn-container .action-btn-group span.action-disabled {
	color: #c8c9cc;
}
.action-btn-container .action-btn-group span.cart-item-count {
	margin: 0 2px;
}

.action-btn-container .action-btn-group span:first-child, .action-btn-container  .action-btn-group span.cart-item-count, .action-btn-container .action-btn-group span:last-child {
    background: #f7f7f7;
    width: 24px;
    height: 24px;
}
.buy-count {
    color: #fe0000;
}
.confirm-btn {
    width: 100%;
    height: 44px;
    background: #dd3022;
    color: #fff;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.confirm-btn.confirm-btn-disabled {
	background: rgba(0, 0, 0, .6);
}
.mint-popup-4 {
    width: 100%;
}
.specs-item-button.active {
    background: red;
    color: #fff;
}
.specs-item-button.disabled {
    background: #eee;
}
.specs-item-button.normal {
    background: #fff;
}
.product-spec-wrap {
	max-height: 400px;
	overflow-y: auto;
}
</style>
<template>
	<mt-popup v-model="joinCartModalVisible" @input="cartModalChange" :lock-scroll="true" position="bottom" class="mint-popup-4">
	    <div class="product-info scale-1px">
	        <div class="product-image">
	            <img :src="curProductItem.picture||productInfo.productImg">
	        </div>
	        <div class="product-tip">
	            <div class="product-price">
	                <span class="dp-price">¥{{ productPriceObj.dpPrice }}</span><span class="sc-price" v-if="productPriceObj.dpPrice != productPriceObj.scPrice">¥{{ productPriceObj.scPrice }}</span>
	            </div>
	            <div class="product-name">
	                {{ productInfo.name }}
	            </div>
	            <div class="product-detail" >
		            <div class="selected-items" v-if="specs&&specs.length||attributes.length||addons.length">
		                {{ showSpec ? '已选:'+showSpec : '已选:' }}
		            </div>
		            <span class="qty" v-if="specs&&specs.length && SKUResult[haveChangedId.join(';')].inventoryQty != -1">库存:{{SKUResult[haveChangedId.join(";")].inventoryQty||0}}</span>
		        </div>
	        </div>
	        <span class="icon-close" @click="joinCartModalVisible = false"></span>
	    </div>
	    <div class="product-spec-wrap">
		    <div class="specs-container" v-if="specs&&specs.length">
		        <div class="specs-item scale-1px" v-for="(specsItem, index) in specs" :key="specsItem.id">
		            <div class="specs-item-name">
		                {{specsItem.name}}
		            </div>              
		            <div class="clearfix">
		                <span class="specs-item-button pull-left" @click="tabInfoChange(index, specsItemIndex, child, $event)" :class="{disabled:child.notClick, active:child.isActive}"  v-for="(child, specsItemIndex) in specsItem.child" :key="child.id">
		                    {{child.name}}
		                </span>
		            </div>
		        </div>
		    </div>

		    <div class="specs-container" v-if="attributes&&attributes.length">
		        <div class="specs-item scale-1px" v-for="(attribute, index) in attributes" :key="attribute.attributeId">
		            <div class="specs-item-name">
		                {{attribute.attributeName}}
		            </div>              
		            <div class="clearfix">
		                <span class="specs-item-button pull-left" :class="{active:attribute.selectAttributeItemId == attributeItem.attributeItemId}" @click="setAttributeItemId(attribute, attributeItem)"  v-for="attributeItem in attribute.attributeItemList" :key="attributeItem.attributeItemId">
		                    {{attributeItem.attributeItemName}}
		                </span>
		            </div>
		        </div>
		    </div>

		    <div class="specs-container" v-if="addons&&addons.length">
		        <div class="specs-item scale-1px" v-for="(addon, index) in addons" :key="addon.addonId">
		            <div class="specs-item-name">
		                {{addon.addonName}}
		            </div>              
		            <div class="clearfix">
		                <span class="specs-item-button pull-left"  v-for="addonItem in addon.addonItemList" :class="{active:addon.selectAddonItemId == addonItem.addonItemId}" @click="setAddonItemId(addon, addonItem)" :key="addonItem.addonItemId">
		                    {{addonItem.addonItemName}} {{addonItem.price ? '¥'+ addonItem.price : ''}}
		                </span>
		            </div>
		        </div>
		    </div>

		    <div class="product-num">
		        <div class="tip">
		            购买数量：
		        </div>
		        <div class="action-btn-container clearfix">
		            <div class="action-btn-group">
		                <span @click="desCount" :class="[curCount <=1 ?'action-disabled':'']">-</span><span class="buy-count cart-item-count">{{curCount}}</span><span @click="addCount">+</span>
		            </div>
		        </div>
		    </div>
	    </div>
	    <div class="split-line"></div>
	    <div class="confirm-btn" :class="[btnDisabledStatus ? 'confirm-btn-disabled' : '']" @click="addToCart">
            确定
        </div>
	</mt-popup>
</template>
<script type="text/javascript">
	import utils from '@utils'
	import { addToCart } from './api'
	export default {
		data() {
			return {
				productInfo: {
	                sowImg: [],
	                productItems: [],
	                id: null,
	                code: null,
	                name: '',
	                productImg: '',
	                scPrice: '',
	                dpPrice: '',
	                type: '',
	                productDetail: '',
	            },

	            curCount: 1,
				specs: [],
				attributes: [],
	            productItemsObj: {},
	            SKUResult: {},
	            haveChangedId: [],

	            joinCartModalVisible: this.value,

	            attributes: [],
	            addons: []
			}
		},
		props: {
			value: {
				required: true
			}, 
			goodsItemDetail: {
				required: true
			},
			actionType: {
				type: String,
				default: 'addCart'
			}
		},
		computed:{
	        curProductItem: function() {
	            if(this.productItemsObj[this.haveChangedId.join(";")]) {
	                return this.productItemsObj[this.haveChangedId.join(";")]
	            } else {
	                return {};
	            }
	        },
	        btnDisabledStatus() {
	        	var data = this.productInfo
	        	for(var i=0;i<this.attributes.length;i++) {
	        		if(!this.attributes[i].selectAttributeItemId) {
	        			return true
	        		}
	        	}

	        	if(data.type == 'MULTIPLE') {
	        		if(!this.curProductItem.id) {
	        			return true
	        		} else if(this.curProductItem.inventoryQty == -1) {
	        			return false
	        		} else if(this.curProductItem.inventoryQty<=0) {
			          return true
			        }
	        	}

	        	return false
	        },
	        productPriceObj() {
	        	let dpPrice = this.curProductItem.dpPrice||this.productInfo.dpPrice
	        	let scPrice = this.curProductItem.scPrice||this.productInfo.scPrice
	        	
	        	this.addons.filter(item => item.selectAddonItemId).forEach(item => {
	        		for(var i=0;i<item.addonItemList.length;i++) {
	        			if(item.addonItemList[i].addonItemId == item.selectAddonItemId) {
	        				console.log('item.addonItemList', item.addonItemList)
	        				dpPrice += item.addonItemList[i].price;
	        				scPrice += item.addonItemList[i].price;
	        				break;
	        			}
	        		}
	        	})

	        	return {
	        		dpPrice: dpPrice,
	        		scPrice: scPrice
	        	}
	        },
	        showSpec() {
	        	var data = this.productInfo;
	        	var specs = []

	        	if(data.type == 'MULTIPLE') {
	        		this.specs.forEach(item => {
	        			for (var i=0;i<item.child.length;i++) {
	        				if(item.child[i].isActive) {
	        					specs.push(item.child[i].name)
	        					return
	        				}
	        			}
	        		})
	        	}

	        	this.attributes.forEach(item => {
	        		for(var i=0;i<item.attributeItemList.length;i++) {
	        			if(item.attributeItemList[i].attributeItemId == item.selectAttributeItemId) {
	        				specs.push(item.attributeItemList[i].attributeItemName);
	        				return
	        			}
	        		}
	        	})

	        	this.addons.forEach(item => {
	        		for(var i=0;i<item.addonItemList.length;i++) {
	        			if(item.addonItemList[i].addonItemId == item.selectAddonItemId) {
	        				specs.push(item.addonItemList[i].addonItemName);
	        			}
	        		}
	        	})

	        	return specs.join(",")
	        }
	    },
	    mounted() {
	    	var data = JSON.parse(JSON.stringify(this.goodsItemDetail));
            // SKU 逻辑
            if(data.type == 'MULTIPLE') { //多sku
		    	var defaultSku = data.productItems.filter(item=>item.inventoryQty>0)[0];
	            
	            this.initKeys(data.specs);
	            this.initProductItems(data.productItems);
	            this.initSKU();
	            this.initDisabledSpecItem();
	            if(defaultSku) {
	            	var specs = defaultSku.specs.slice(0)
	            	this.initDefaultSku(data.specs, specs)
	            }
            }

            // 属性
        	this.attributes = (data.attributes||[]).map(item=> {
        		item.selectAttributeItemId = item.attributeItemList[0].attributeItemId
        		return Object.assign({}, item)
        	})

            // 附属品
        	this.addons = (data.addons||[]).map(item=> {
        		item.selectAddonItemId = ''
        		return Object.assign({}, item)
        	})

        	delete data.attributes;
		    delete data.addons;
		    delete data.specs;
		    delete data.sowImg;

        	this.productInfo = data;
	    },
	    methods: {
	    	initKeys: function(specs) {
	            for(var i=0;i<specs.length;i++) {
	                var curSpec = specs[i];
	                for(var j=0;j<curSpec.child.length;j++) {
	                    curSpec.child[j].isActive = false;
	                    curSpec.child[j].notClick = false;
	                }
	            }
	            this.specs = specs;
	        },
	        initProductItems: function(productItems) {
	            var productItemsObj = {};
	            for(var i=0;i<productItems.length;i++) {
	                var specsKey = productItems[i].specs;
	                for(var j=0;j<this.specs[0].child.length;j++) {
			        	if(specsKey[0].id == this.specs[0].child[j].id) {
			              	productItems[i].picture = this.specs[0].child[j].url;
			              	break;
			            }
			        }
			        
	                specsKey = specsKey.sort(function(itemA, itemB) {
	                    return parseInt(itemA.id) - parseInt(itemB.id);
	                }).map(item => item.id).join(";");
	                productItemsObj[specsKey] = productItems[i];
	            }

	            this.productItemsObj = productItemsObj;
	        },
	        //获得对象的key
	        getObjKeys(obj) {
	            if(obj !== Object(obj)) throw new TypeError('Invalid object');
	            var keys = [];
	            for(var key in obj)
	                if(Object.prototype.hasOwnProperty.call(obj, key))
	                    keys[keys.length] = key;
	            return keys;
	        },
	        addToSKUResult(combArrItem, sku) {
	            var key = combArrItem.join(";");
	            if(this.SKUResult[key]) { //SKU信息key属性·
	                this.SKUResult[key].inventoryQty += sku.inventoryQty;
	            } else {
	                this.SKUResult[key] = {
	                    inventoryQty: sku.inventoryQty
	                };
	            }
	        },
	        combinationConcat(aData) {
	            var result = [];
	            for(var i=1;i<=aData.length;i++) {
	                result = result.concat(aData.combination(i))
	            }
	            return result;
	        },
	        initSKU() {
	            var i, j, skuKeys = this.getObjKeys(this.productItemsObj);
	            for(i = 0; i < skuKeys.length; i++) {
	                var skuKey = skuKeys[i]; //一条SKU信息key
	                var sku = this.productItemsObj[skuKey]; //一条SKU信息value
	                var skuKeyAttrs = skuKey.split(";"); //SKU信息key属性值数组
	                skuKeyAttrs.sort(function(value1, value2) {
	                    return parseInt(value1) - parseInt(value2);
	                });
	                //对每个SKU信息key属性值进行拆分组合
	                var combArr = this.combinationConcat(skuKeyAttrs);
	                for(j = 0; j < combArr.length; j++) {
	                    this.addToSKUResult(combArr[j], sku);
	                }
	            }
	        },
	        initDisabledSpecItem() {
	            for(let i=0;i<this.specs.length;i++){
	                for(let j=0;j<this.specs[i].child.length;j++){
	                    if(this.SKUResult[this.specs[i].child[j].id] == null){
	                        this.specs[i].child[j].notClick = true;
	                    }
	                }
	            }
	        },
	        initDefaultSku(specList, specArray) {
			    for(var i=0;i<specList.length;i++) {
			      for(var j=0;j<specList[i].child.length;j++) {
			      	if(specArray[i]) {
				        if(specArray[i].id === specList[i].child[j].id) {
				          this.tabInfoChange(i, j)
				          break;
				        }
				    }
			      }
			    }
	        },
	        tabInfoChange(index,cindex,cid,e){
	            let specs = JSON.parse(JSON.stringify(this.specs))
	            let orderInfoChild = specs[index].child;/*当前点击的规格的所有子属性内容*/
	            //选中自己，兄弟节点取消选中
	            if(orderInfoChild[cindex].notClick != true){
	                if(orderInfoChild[cindex].isActive == true){
	                    orderInfoChild[cindex].isActive = false;
	                }else{
	                    for(let i=0;i<orderInfoChild.length;i++){
	                        orderInfoChild[i].isActive = false;
	                    }
	                    orderInfoChild[cindex].isActive = true;
	                }
	            }
	            
	            //已经选择的节点
	            let haveChangedId = [];
	            for(let i=0;i<specs.length;i++){
	                for(let j=0;j<specs[i].child.length;j++){
	                    if(specs[i].child[j].isActive == true){
	                        haveChangedId.push(specs[i].child[j].id);
	                    }
	                }
	            }
	            if(haveChangedId.length) {
	                //获得组合key价格
	                haveChangedId.sort(function(value1, value2) {
	                    return parseInt(value1) - parseInt(value2);
	                });
	                
	                this.haveChangedId = haveChangedId;

	                var len = haveChangedId.length;
	                
	                //用已选中的节点验证待测试节点 
	                let daiceshi = [];//待测试节点
	                let daiceshiId = [];
	                for(let i=0;i<specs.length;i++){
	                    for(let j=0;j<specs[i].child.length;j++){
	                        if(specs[index].child[cindex].id != specs[i].child[j].id){
	                            daiceshi.push({
	                                index:i,
	                                cindex:j,
	                                id: specs[i].child[j].id
	                            });
	                            daiceshiId.push(specs[i].child[j].id);
	                        }
	                    }
	                }

	                for(let i=0;i<haveChangedId.length;i++){
	                    var indexs = daiceshiId.indexOf(haveChangedId[i]);
	                    if (indexs > -1) {
	                        daiceshi.splice(indexs, 1);
	                    }
	                }
	                for(let i=0;i<daiceshi.length;i++){
	                    let testAttrIds = []; //从选中节点中去掉选中的兄弟节点
	                    let siblingsId = "";
	                    for(let m=0; m<specs[daiceshi[i].index].child.length; m++){
	                        if(specs[daiceshi[i].index].child[m].isActive == true){
	                            siblingsId = specs[daiceshi[i].index].child[m].id;
	                        }
	                    }
	                    if(siblingsId != ""){
	                        for(let j=0;j<len;j++){
	                            (haveChangedId[j] != siblingsId) && testAttrIds.push(haveChangedId[j]);
	                        }
	                    }else{
	                        testAttrIds = haveChangedId.concat();
	                    }
	                    testAttrIds = testAttrIds.concat(this.specs[daiceshi[i].index].child[daiceshi[i].cindex].id);
	                    testAttrIds.sort(function(value1, value2) {
	                        return parseInt(value1) - parseInt(value2);
	                    });
	                    if(!this.SKUResult[testAttrIds.join(';')]) {
	                        specs[daiceshi[i].index].child[daiceshi[i].cindex].notClick = true;
	                        specs[daiceshi[i].index].child[daiceshi[i].cindex].isActive = false;
	                    } else {
	                        specs[daiceshi[i].index].child[daiceshi[i].cindex].notClick = false;
	                    }
	                }
	            } else {
	            	this.haveChangedId = haveChangedId;
	                //设置属性状态
	                for(let i=0;i<specs.length;i++){
	                    for(let j=0;j<specs[i].child.length;j++){
	                        if(this.SKUResult[specs[i].child[j].id]){
	                            specs[i].child[j].notClick = false;
	                            specs[i].child[j].isActive = false;
	                        }else{
	                            specs[i].child[j].notClick = true;
	                            specs[i].child[j].isActive = false;
	                        }
	                    }
	                }
	            }
	            this.specs = specs;
	        },
	        setAddonItemId(addon, addonItem) {
	        	if(addon.selectAddonItemId == addonItem.addonItemId) {
	        		addon.selectAddonItemId = '';
	        	} else {
	        		addon.selectAddonItemId = addonItem.addonItemId;
	        	}
	        },
	        setAttributeItemId(attribute, attributeItem) {
	        	attribute.selectAttributeItemId = attributeItem.attributeItemId;
	        },
	        addToCart(actionType) {
	        	if(this.attributes.length) {
	        		if(this.btnDisabledStatus) {
	        			this.$toast({
	                        message: '请选择商品规格',
	                        position: 'top',
	                        duration: 5000
	                    });
	                    return
	        		}
	        	}

	        	if(this.productInfo.type == 'MULTIPLE') {
	        		if(!this.curProductItem.id) {
	        			this.$toast({
	                        message: '请选择商品规格',
	                        position: 'top',
	                        duration: 5000
	                    });
	                    return
	        		} else if(this.curProductItem.inventoryQty != -1 && this.curProductItem.inventoryQty <= 0) {
			          	this.$toast({
	                        message: '商品库存不足',
	                        position: 'top',
	                        duration: 5000
	                    });
			          	return;
			        }
	        	}

                var params = {
                    number: this.curCount,
                    productId: this.productInfo.id
                };
                if(this.productInfo.type == 'MULTIPLE') {
                	params.productItemId = this.curProductItem.id
                }

                params.attributes = this.attributes.map(item => {
                	return {
                		attributeId: item.attributeId,
                		attributeItemId: item.selectAttributeItemId
                	}
                })

                params.addons = this.addons.filter(item=> item.selectAddonItemId).map(item => {
                	return {
                		addonId: item.addonId,
                		addonItemId: item.selectAddonItemId
                	}
                })

                this.cartCount += this.curCount;
                if(this.actionType == 'addCart') {
	                addToCart(params).then(() => {
	                    this.$toast({
	                        message: '已添加到购物车',
	                        position: 'center'
	                    });
	                    this.joinCartModalVisible = false;
	                    this.$emit('addCartSuccess');
	                },() => {
	                    this.$toast({
	                        message: '添加到购物车失败',
	                        type: 'error',
	                        position: 'center'
	                    });
	                    this.cartCount--;
	                })
	            } else {
	            	this.goToCheckOrder()
	            }
	        },
	        desCount() {
	            if(this.curCount<=1) {
	                this.$toast({
	                    message: '数量最少为1',
	                    type: 'error',
	                    position: 'top'
	                });
	            } else {
	                this.curCount--;
	            }
	        },
	        addCount() {
	            if(this.curCount>=999) {
	                this.$toast({
	                    message: '数量较大暂不支持',
	                    type: 'error',
	                    position: 'top'
	                });
	            } else {
	                this.curCount++;
	            }
	        },
	        goToCheckOrder() {

	        	let attributes = this.attributes.map((item) => {
			        return {
			          	attributeId: item.attributeId,
			          	attributeItemId: item.selectAttributeItemId,
			        };
			      });

			    let addons = this.addons
			        .filter((item) => item.selectAddonItemId)
			        .map((item) => {
			          	return {
			            	addonId: item.addonId,
			            	addonItemId: item.selectAddonItemId,
			          	};
			        });
			    let url = `/check_order.html?productId=${this.productInfo.id}&productItemId=${this.curProductItem.id || ''}&number=${this.curCount}`
			    if(attributes.length) {
			        url+= "&attributes="+encodeURIComponent(JSON.stringify(attributes))
			    }
			    if(addons.length) {
			        url+= "&addons="+encodeURIComponent(JSON.stringify(addons))
			    }

	            utils.goToPage(url);
	        },
	        cartModalChange(val) {
	            setTimeout(()=> {
	            	this.$emit("input", this.joinCartModalVisible);
	            }, 200)
	        }
	    }
	}
</script>